package com.om.abom.utils.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Slf4j
public class ShellExecutorLocal
{
    /**
     * Java执行Linux命令（本地调用）
     *
     * @param command 命令
     * @return 是否调用成功
     */
    public static String execLocalCmd(String command)
    {
        String result = null;
        try {
            Process proc = Runtime.getRuntime().exec(command);
            String inStr = consumeInputStream(proc.getInputStream());
            // 标准错误流（必须写在 waitFor 之前）
            String errStr = consumeInputStream(proc.getErrorStream());

            int retCode = proc.waitFor();
            if (retCode == 0 || StringUtils.isEmpty(errStr)) {
                result = inStr;
            } else {
                result = errStr;
            }
        } catch (IOException | InterruptedException e) {
            log.error("exception message: ", e);
        }
        return result;
    }


    /**
     * 消费输入流信息
     *
     * @param is 输入流
     * @return 输出结果
     */
    public static String consumeInputStream(InputStream is)
    {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String s;
            StringBuilder sb = new StringBuilder();
            while ((s = br.readLine()) != null) {
                System.out.println(s);
                sb.append(s);
            }
            br.close();
            is.close();
            return sb.toString();
        } catch (IOException e) {
            log.error("exception message: ", e);
        }
        return null;
    }
}


